<script type="text/javascript">
  (function () {

    // NOTE: Keep in sync with helper
    function cleanFilename(aFilename, aDefaultName) {
      // Blacklist problem characters (slashes, colons, etc.).
      var cleanName = (aFilename || '').replace(/[\\\/:*?\'\"<>|#;@=&]/g, '')

      // Make whitespace readable.
      .replace(/(\s|%20)+/g, '_');

      return cleanName || aDefaultName;
    };

    function onDOMContentLoaded(aEv) {
      var username = document.querySelector('input[name="username"]');
      var consent = document.querySelector('input[name="consent"]');
      var phoneInput = document.querySelector('input[name="phone"]');
      var action = document.querySelector('button#action');
      var sendVcodeButton = document.querySelector('span#sendVcode');
      var vcodeInput = document.querySelector('input[name="vcode"]');

      function onInputUsername(aEv) {
        var req = new XMLHttpRequest();
        var wantname = cleanFilename(aEv.target.value, '');

        function show(aConsent) {
          action.innerHTML = action.innerHTML.replace(/注册/, '登录');
          // by ElmerZhang: 登录时，要隐藏电话和验证码字段
          phoneInput.disabled = true;
          vcodeInput.disabled = true;
          phoneInput.parentElement.classList.add('hidden');
          vcodeInput.parentElement.classList.add('hidden');
          action.classList.add('btn-success');
          action.classList.remove('btn-info');

          if (aConsent) {
            consent.checked = false;
          } else {
            consent.checked = true;
          }
        }

        function hide() {
          action.innerHTML = action.innerHTML.replace(/登录/, '注册');
          // by ElmerZhang: 注册时，要显示电话和验证码字段
          phoneInput.disabled = false;
          vcodeInput.disabled = false;
          phoneInput.parentElement.classList.remove('hidden');
          vcodeInput.parentElement.classList.remove('hidden');
          action.classList.remove('btn-success');
          action.classList.add('btn-info');

          consent.checked = false;
        }

        if (wantname) {
          req.open('HEAD', '/api/user/exist/' + wantname);
          req.onreadystatechange = function () {
            if (this.readyState == this.DONE) {
              switch (this.status) {
                case 200:
                  show(/ consent$/.test(this.getResponseHeader('Warning')));
                  break;
                default:
                  hide();
              }
            }
          };
          req.send();
        } else {
          hide();
        }

        if (username.value !== wantname) {
          username.value = wantname;
        }
      }

      // by ElmerZhang: 发送验证码
      function sendVcode() {
        var req = new XMLHttpRequest();
        var phone = phoneInput.value;
        if (!phone) {
          alert('请输入你的手机号码');
          return;
        }

        req.open('POST', '/auth/sendVcode/');
        req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        req.onreadystatechange = function () {
          if (this.readyState === this.DONE) {
            if (this.status === 200) {
              var {success, phoneUsed} = JSON.parse(this.response);
              if (phoneUsed) {
                alert('该号码已经注册，请输入其他手机号码.');
              } else if (success) {
                sendVcodeButton.classList.add('disabled');
                sendVcodeButton.removeEventListener('click', sendVcode);

                var seconds = 60;
                var setter = setInterval(function() {
                  if (seconds > 0) {
                    sendVcodeButton.innerText = ' ' + seconds + ' 秒后重发';
                    seconds--;
                  } else {
                    sendVcodeButton.innerText = '重发验证码';
                    sendVcodeButton.addEventListener('click', sendVcode);
                    sendVcodeButton.classList.remove('disabled');
                    clearInterval(setter);
                  }
                }, 1000);
              } else {
                alert('验证码发送失败，请稍后再试.');
              }
            }
          }
        };
        req.send('phone='+phone);

        console.log('sendVcode');
      }

      if (sendVcodeButton) {
        sendVcodeButton.addEventListener('click', sendVcode);
        sendVcodeButton.innerText = '发送验证码';
      }

      if (username && action) {
        action.innerHTML = action.innerHTML.replace(/Next/, '注册');

        username.addEventListener('input', onInputUsername);
      }
    }

    document.addEventListener('DOMContentLoaded', onDOMContentLoaded);

  })();
</script>
